package com.lixianhe.onlineexam.controller;

import com.lixianhe.onlineexam.util.R;
import com.lixianhe.onlineexam.pojo.Teacher;
import com.lixianhe.onlineexam.service.TeacherService;
import com.lixianhe.onlineexam.util.ApiResultHandler;
import com.lixianhe.onlineexam.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/teachers/{page}/{size}")
    public R teachers(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageBean<Teacher> teacherPageInfo = teacherService.selectTeacherByPage(page, size);
        return ApiResultHandler.buildApiResult(200, "查询教师", teacherPageInfo);
    }

    @PostMapping("/teacher")
    public R addTeacher(@RequestBody Teacher teacher) {
        int e = teacherService.addTeacher(teacher);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "增加成功", e);
        return ApiResultHandler.buildApiResult(400, "增加失败", e);
    }

    @GetMapping("/teacher/{id}")
    public R teacher(@PathVariable("id") Integer id) {
        Teacher teacher = teacherService.selectTeacherById(id);
        return ApiResultHandler.buildApiResult(200, "查询教师", teacher);
    }

    @PutMapping("/teacher")
    public R updateTeacher(@RequestBody Teacher teacher) {
        int e = teacherService.updateTeacher(teacher);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "更新成功", e);
        return ApiResultHandler.buildApiResult(400, "更新失败", e);
    }

    @DeleteMapping("/teacher/{id}")
    public R deleteTeacher(@PathVariable("id") Integer id) {
        int e = teacherService.deleteTeacher(id);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "删除成功", e);
        return ApiResultHandler.buildApiResult(400, "删除失败", e);
    }

    @PostMapping("/admin_teacherExit")
    public R exit(HttpServletRequest request) {
        String admin = (String) request.getSession().getAttribute("admin");
        String teacher = (String) request.getSession().getAttribute("teacher");
        if (admin != null) request.getSession().removeAttribute("admin");
        if (teacher != null) request.getSession().removeAttribute("teacher");
        return ApiResultHandler.buildApiResult(200, "退出成功", null);
    }

    @PutMapping("/teacherPWD")
    public R updatePwd(@RequestBody Teacher teacher) {
        teacherService.updatePwdTeacher(teacher);
        return ApiResultHandler.buildApiResult(200, "密码更新成功", null);
    }
}
